package com.yqg.manage.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.yqg.manage.common.interceptor.SysLog;
import com.yqg.manage.controller.dto.UserDTO;
import com.yqg.manage.controller.dto.UserPasswordDTO;
import com.yqg.manage.entity.*;
import com.yqg.manage.mapper.RoleMapper;
import com.yqg.manage.mapper.UserMapper;
import com.yqg.manage.service.IRecordOperateService;
import com.yqg.manage.service.IRoleService;
import com.yqg.manage.service.IUnitResponsibilityService;
import com.yqg.manage.utils.Constants;
import com.yqg.manage.utils.IPUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.yqg.manage.common.Result;
import com.yqg.manage.service.IUserService;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * UserController 前端控制器
 *
 * @author suzhuang
 * @since 2023-07-05
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private IUserService userService;
    @Resource
    private IUnitResponsibilityService unitResponsibilityService;
    @Resource
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    IPUtils ipUtils;

    @Autowired
    private IRecordOperateService recordOperateService;

    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody UserDTO userDTO) {
        String account = userDTO.getAccount();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(account) || StrUtil.isBlank(password)) {
            return Result.error(Constants.String_CODE_400, "参数错误");
        }
        UserDTO dto = userService.login(userDTO);
        RecordOperate recordOperate = new RecordOperate();
        recordOperate.setUserId(userDTO.getId().longValue());
        recordOperate.setIsDelete(0);
        recordOperate.setOperateType("com.yqg.protection.controller.UserController.login()");
        recordOperate.setContent("用户登录");
        recordOperate.setUserIp(ipUtils.getIpAddr(request));
        recordOperate.setCreatedTime(LocalDateTime.now());
        recordOperateService.save(recordOperate);
        return Result.success(dto);
    }

    /**
     * 新增或者更新
     */
    @PostMapping("/edit")
    @SysLog("新增或者更新用户")
    public Result save(@RequestBody @Valid User user) {
        //新增的时候判断是否存在重复account
        if (user.getId() == null) {//新增用户
            QueryWrapper<User> accountWrapper = new QueryWrapper<>();
            accountWrapper.eq("is_delete", "0");
            accountWrapper.eq("account", user.getAccount());
            User userAccount = userService.getOne(accountWrapper);
            if (userAccount != null) {
                return Result.error("400", "该账户已存在");
            }
            if (user.getSex() == null || user.getSex().isEmpty()) {
                user.setSex("2");
            }
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            user.setIsDelete("0");
            user.setPassword(SecureUtil.md5("123456"));
        } else {//修改
            if (user.getSex().equals("男")) {
                user.setSex("0");
            } else if (user.getSex().equals("女")) {
                user.setSex("1");
            } else if (user.getSex().equals("未知")) {
                user.setSex("2");
            }
            user.setUpdateTime(new Date());
        }
        boolean b = userService.saveOrUpdate(user);
//        副主任负责单位记录处理
        if (user.getUserRole() == 8) {
            Long userId = user.getId();
            List<Long> unitIds = user.getUnitIds() != null ? user.getUnitIds() : new ArrayList<>();

            LambdaQueryWrapper<UnitResponsibility> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UnitResponsibility::getUserId, userId);

            // 如果新unitIds为空，直接删除所有
            if (unitIds.isEmpty()) {
                unitResponsibilityService.remove(queryWrapper);
            } else {
                Set<Long> newUnitIds = new HashSet<>(unitIds);

                // 删除不在新列表中的记录
                LambdaQueryWrapper<UnitResponsibility> deleteWrapper = new LambdaQueryWrapper<>();
                deleteWrapper.eq(UnitResponsibility::getUserId, userId)
                        .notIn(UnitResponsibility::getUnitId, newUnitIds);
                unitResponsibilityService.remove(deleteWrapper);

                // 查询现有的unitIds
                List<Long> existingUnitIds = unitResponsibilityService.list(queryWrapper)
                        .stream()
                        .map(UnitResponsibility::getUnitId)
                        .collect(Collectors.toList());

                // 3. 批量新增不存在的记录
                List<UnitResponsibility> toAddList = newUnitIds.stream()
                        .filter(unitId -> !existingUnitIds.contains(unitId))
                        .map(unitId -> {
                            UnitResponsibility ur = new UnitResponsibility();
                            ur.setUserId(userId);
                            ur.setUnitId(unitId);
                            return ur;
                        })
                        .collect(Collectors.toList());

                if (!toAddList.isEmpty()) {
                    unitResponsibilityService.saveBatch(toAddList);
                }
            }

        }
        return Result.success(b);
    }

    /**
     * 删除
     */
    @GetMapping("delete/{id}")
    @SysLog("删除用户")
    public Result delete(@PathVariable Integer id) {
        User user = userService.getById(id);
        user.setIsDelete("1");
        // 若是副主任，同时删除负责单位
        if (user.getUserRole() == 8) {
            LambdaQueryWrapper<UnitResponsibility> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UnitResponsibility::getUserId, user.getId());
            unitResponsibilityService.remove(queryWrapper);
        }

        return Result.success(userService.saveOrUpdate(user));
    }

    /**
     * 查询所有
     */
    @GetMapping("/all")
    public Result findAll() {
        return Result.success(userService.listAll());
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        User user = userMapper.getUserById(id);
        return Result.success(user);
    }

    /**
     * 根据科室id和角色id查询
     */
    @ApiOperation("根据科室id和角色id查询")
    @GetMapping("/findUserDataByDepartmentId")
    public Result findUserDataByDepartmentId(@RequestParam Long departmentId, @RequestParam Long userRole) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserRole, userRole)
                .eq(User::getDepartmentId,departmentId)
                .eq(User::getIsDelete, "0");
        return Result.success(userService.list(wrapper));
    }

    /**
     * 根据单位和角色获取用户用户
     */
    @GetMapping("/findUserDataByUnitIdAndRoleId")
    public Result findUserDataByUnitIdAndRoleId(@RequestParam Long unitId, @RequestParam Long userRole) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserRole, userRole)
                .eq(User::getUnitId,unitId)
                .eq(User::getIsDelete, "0");
        return Result.success(userService.list(wrapper));
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public Result findPage(
            @RequestParam Long pageNum,
            @RequestParam Long pageSize,
            @RequestParam(required = false) Long unitId,
            @RequestParam(required = false) String userName,
            @RequestParam Long userId,
            @RequestParam(required = false) Long roleLevel) {
        pageNum = (pageNum - 1) * pageSize;
        List<User> userList = userMapper.getPageList(pageNum, pageSize, unitId, userName, userId, roleLevel);
        Integer count = userMapper.getPageListCount(unitId, userName, userId, roleLevel);
        Map<String, Object> map = new HashMap<>();
        map.put("records", userList);
        map.put("total", count);
        return Result.success(map);
    }

    /**
     * 副主任分页查询
     */
    @GetMapping("/deputyDirectorFindPage")
    public Result deputyDirectorFindPage(@RequestParam Long pageNum,
                                         @RequestParam Long pageSize,
                                         @RequestParam(required = false) String userName,
                                         @RequestParam(required = false) Long unitId,
                                         @RequestParam Long userId,
                                         @RequestParam(required = false) Long roleLevel) {
        pageNum = (pageNum - 1) * pageSize;
        List<User> userList = userMapper.deputyDirectorFindPage(pageNum, pageSize, unitId, userName, userId, roleLevel);
        Integer count = userMapper.deputyDirectorFindPageCount(unitId, userName, userId, roleLevel);
        Map<String, Object> map = new HashMap<>();
        map.put("records", userList);
        map.put("total", count);
        return Result.success(map);
    }


    @GetMapping("/identificationNumber")
    public Result findListByidentificationNumber() {
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.isNotNull(User::getIdentificationNumber);
        return Result.success(userService.list(userQueryWrapper));
    }

    /**
     * 重置用户密码
     */
    @GetMapping("/resetPwd")
    @ApiOperation("重置用户密码")
    @SysLog("重置用户密码")
    public Result resetPwd(@RequestParam Integer id) {
        userService.resetPwd(id, SecureUtil.md5("123456"), new Date());
        return Result.success(true);
    }

    @PostMapping("changePwd")
    @ApiOperation("修改用户密码")
    @SysLog("修改用户密码")
    public Result changePwd(@RequestBody UserPasswordDTO userPasswordDTO) {
        String account = userPasswordDTO.getAccount();
        String password = SecureUtil.md5(userPasswordDTO.getPassword());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", account);
        queryWrapper.eq("password", password);
        queryWrapper.eq("is_delete", "0");
        User one = userService.getOne(queryWrapper);
        if (one == null) {
            return Result.error("密码错误");
        } else {
            String newPassword = SecureUtil.md5(userPasswordDTO.getNewPassword());
            one.setPassword(newPassword);
            userService.saveOrUpdate(one);
            return Result.success("修改成功");
        }

    }

    @GetMapping("/findAllName")
    public Result findAllName() {
        return Result.success(userService.listAllName());
    }

    /**
     * @return 所有有执法证件号的用户
     */
    @ApiOperation("所有有执法证件号的用户")
    @GetMapping("/allIdentificationNumber")
    public Result allIdentificationNumber() {
        return userService.allIdentificationNumber();
    }

}

